<!-- 用户权限弹窗 -->
<template>
  <ele-modal
    :width="460"
    :visible="visible"
    :confirm-loading="loading"
    title="设置权限"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ md: 5, sm: 5, xs: 24 }"
      :wrapper-col="{ md: 19, sm: 19, xs: 24 }"
    >
      <a-form-item label="权限组织" name="groupOrg">
        <a-select
          placeholder="请选择权限组织"
          v-model:value="form.groupOrg"
          allow-clear
          :loading="orgLoading"
        >
          <a-select-option
            v-for="item in groupOrgOptions"
            :key="item.id"
            :value="item.groupOrg"
          >
            {{ item.groupOrg }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="其他对讲组权限" name="groupNos">
        <a-input
          allow-clear
          :maxlength="20"
          placeholder="请输入对讲组编号"
          v-model:value="form.groupNos"
        />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue/es';
  import useFormData from '@/utils/use-form-data';
  import { setUserDataPermission, getUserDataPermission, getAllDataPermission } from '@/api/system/role';

  const emit = defineEmits(['done', 'update:visible']);

  const props = defineProps({
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  });

  //
  const formRef = ref(null);

  // 提交状态
  const loading = ref(false);

  const orgLoading = ref(false); // 组织加载状态
  const groupOrgOptions = ref([]); // 组织选项
  const userId = ref(null);
  // 表单数据
  const { form, resetFields, assignFields } = useFormData({
    userId: undefined,
    groupOrg: '',
    groupNos: undefined
  });

  // 表单验证规则
  const rules = reactive({
    groupOrg: [
      {
        required: true,
        message: '请选择权限组织',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        setUserDataPermission(form)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  /* 获取权限组织列表 */
  const getGroupOrgList = () => {
    orgLoading.value = true;
    getAllDataPermission() // 获取所有权限组织列表
      .then(data => {
        console.log('groupOrgOptions===>',data);
        groupOrgOptions.value = data;
        orgLoading.value = false;
      })
      .catch(e => {
        orgLoading.value = false;
        message.error('获取组织列表失败: ' + e.message);
      });
  };

  /* 更新visible */
  const updateVisible = (value) => {
    emit('update:visible', value);
  };

  const fetchUserPermissions = async (userId) => {
    try {
      const data = await getUserDataPermission(userId);
      console.log('fetchUserPermissions===>', data);
      assignFields({
        userId: userId,
        groupOrg: data.groupOrg,  // 根据实际接口返回字段调整
        groupNos: data.groupNos
      });
    } catch (e) {
      message.error('获取权限信息失败: ' + e.message);
    }
  };

  watch(
    () => props.visible,
    async (visible) => {
      if (visible) {
        // 打开弹窗时获取所有权限组织
        getGroupOrgList();
        if (props.data && props.data.userId) {
          const userId = props.data.userId;
          // 先重置表单
          resetFields();
          console.log('watch...props.data===>', props.data, userId);
          assignFields(props.data);
          // 获取用户权限信息
          await fetchUserPermissions(userId);
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>
